
package com.neo;

import java.io.IOException;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;


// @Import(javax.servlet.ServletResponse) 将第三方包中类的bean对象放入IoC容器中, 对象的的名称默认类全路径
@SpringBootConfiguration //和Configuration没有差别, 表示是一个springboot项目而已
// @Configuration   //表示这是一个配置类, 一般和bean配合使用
public class WebConfiguration {
    
    @Bean  //向ioc容器中放入bean对象, 默认对象默认单例
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }

    @Bean(name="remoteIpFilter10")   //重新设置bean对象名称, 默认是方法名
    public RemoteIpFilter remoteIpFilter2() {
        return new RemoteIpFilter();
    }

    @Scope("prototype")  //表示每次从容器中getbean对象时都会产生一个新对象
    @Bean  //向ioc容器中放入bean对象, 默认单例
    public RemoteIpFilter remoteIpFilter1() {
        return new RemoteIpFilter();
    }

    //环境中有org.apache.catalina.filters.RemoteIpFilter类, 才往IoC容器中放入bean对象
    @ConditionalOnClass(name = "org.apache.catalina.filters.RemoteIpFilter")
    @Bean  //向ioc容器中放入bean对象, 默认单例
    public RemoteIpFilter remoteIpFilter3() {
        return new RemoteIpFilter();
    }
    
    @Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }
    
    public class MyFilter implements Filter {
		@Override
		public void destroy() {
			// TODO Auto-generated method stub
		}

		@Override
		public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
				throws IOException, ServletException {
			// TODO Auto-generated method stub
			HttpServletRequest request = (HttpServletRequest) srequest;
			System.out.println("this is MyFilter,url :"+request.getRequestURI());
			filterChain.doFilter(srequest, sresponse);
		}

		@Override
		public void init(FilterConfig arg0) throws ServletException {
			// TODO Auto-generated method stub
		}
    }
}



